<?php
namespace app\api\model\user;

use app\common\exception\BaseException;
use app\common\model\user\CouponLog as CouponLogModel;
use app\api\model\points\Goods as GoodsModel;
/**
 * 用户返现劵模型
 * Class Couponlog
 * @package app\api\model\user
 */
class CouponLog extends CouponLogModel
{

    /**
     * 获取用户返现券列表
     * @param $user_id
     * @param string $type
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList($user_id, $type = 'not_use')
    {
        // 筛选条件
        $filter = [];
        // 订单数据类型
        switch ($type) {
            case 'not_use';
                $filter['become_time'] = ['<=', time()];
                $filter['scene'] = 10;
                break;
            case 'is_use';
                $filter['scene'] = 20;
                break;
            case 'is_become';
                $filter['scene'] = 10;
                $filter['become_time'] = ['>=', time()];
                break;
        }
        $data =  $this->where('user_id', '=', $user_id)
            ->where($filter)
            ->order(['create_time' => 'desc'])
            ->select();
        return $this->setCouponLogDataForApi($data);
    }

    /**
     * 处理数据
     * @param $data
     * @return array
     */
    private function setCouponLogDataForApi($data)
    {
        if (empty($data)) return [];
        foreach ($data as $key => $value) {
            //is_use允许使用 20 不允许使用
            $data[$key]['is_use'] = $value['scene'] == 10 && $value['become_time'] <= time() ? 10 : 20;
            $data[$key]['become_time'] = date("Y-m-d H:i:s", $value['become_time']);
        }
        return $data;
    }

    /**
     * 返现劵详情
     * @param $log_id
     * @param null $user_id
     * @return null|static
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    public static function getCouponLogDetail($log_id, $user_id)
    {
        if (!$coupon = self::get([
            'log_id' => $log_id,
            'user_id' => $user_id,
            'scene' => ['<>', 20]
        ])) {
            throw new BaseException(['msg' => '返现劵不存在']);
        }
        return $coupon;
    }

    /**
     * 获取用户最大消费券金额
     * @param $user_id
     * @return int|mixed|string
     */
    public static function getUserMaxCoupon($user_id)
    {
        return self::where(['user_id' => $user_id, 'scene' => 10])
            ->max('coupon_money');
    }

    /**
     * 获取可用优惠券
     * @param $user_id
     * @param $goods_id
     * @param $goods_num
     * @param $goods_sku_id
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAllowCouponList($user_id, $goods_id, $goods_num, $goods_sku_id)
    {
        $goods = GoodsModel::detail($goods_id);
        // 判断商品是否下架
        if (!$goods || $goods['is_delete'] || $goods['goods_status']['value'] != 10) {
            throw new BaseException(['msg' => '很抱歉，商品信息不存在或已下架']);
        }
        // 商品sku信息
        $goods['goods_sku'] = $goods->getGoodsSku($goods_sku_id);
        // 商品单价
        $goods['goods_price'] = $goods['goods_sku']['goods_price'];
        // 商品总价
        $goods['total_num'] = $goods_num;
        $goods['total_price'] = $totalPrice = bcmul($goods['goods_price'], $goods_num, 2);
        return $this->where('user_id', '=', $user_id)
            ->where('coupon_money', '>=', $totalPrice)
            ->where('scene', '=', 10)
            ->select();
    }


    /**
     * 兑换商品更新返现劵状态
     * @param $log_id
     * @return false|int
     * @throws \think\exception\DbException
     */
    public static function grantCouponStatus($log_id)
    {
        $model = self::detail($log_id);
        return $model->save([
            'payment_status' => 20,
            'payment_type' => 20,
            'scene' => 20,
        ]);
    }
}